var $ = mdui.$;
var body = $('body');

//----------浅蓝色对话框，time时间后自动关闭----------
function ShowDialog(title, content, time) {
    var inst = mdui.dialog({
        title: title,
        content: content,
        cssClass: 'mdui-color-light-blue-50',
        buttons: [{text: '确认'}]
    });
    inst.open();
    setTimeout(function () {
        inst.close();
    }, time);
}

function GetCookie(name) {
    //获取Cookie
    var strcookie = document.cookie;
    var arrcookie = strcookie.split("; ");//分割
    //遍历匹配
    for (var i = 0; i < arrcookie.length; i++) {
        var arr = arrcookie[i].split("=");
        if (arr[0] === name) {
            return arr[1];
        }
    }
    return "";
}

//----------页面初始化，设置页面标题、修改抽屉导航栏样式----------
function IndexOnload() {
    document.title = '首页';
    $('#drawer_index').addClass('mdui-list-item-active');
}

function LoginOnload() {
    document.title = '登录';
    $('#drawer_center').addClass('mdui-list-item-active');
}

function CenterOnload() {
    document.title = '个人中心';
    $('#drawer_center').addClass('mdui-list-item-active');
}

function SettingsOnload() {
    document.title = '设置中心';
    $('#drawer_settings').addClass('mdui-list-item-active');
    //更新自动登录按钮是否选中
    $('#auto_login_switch')[0].checked = GetCookie('Token') !== '';

}

function ManagementOnload() {
    document.title = '基础信息维护';
    $('#drawer_management').addClass('mdui-list-item-active');
    //添加tab样式
    if (!body.hasClass('mdui-appbar-with-tab'))
        $('body').addClass('mdui-appbar-with-tab');
}

function CourseOnload() {
    document.title = '课程管理';
    $('#drawer_course').addClass('mdui-list-item-active');
    if (!body.hasClass('mdui-appbar-with-tab'))
        body.addClass('mdui-appbar-with-tab');
}

function ScoreOnload() {
    document.title = '成绩信息';
    $('#drawer_score').addClass('mdui-list-item-active');
    if (!body.hasClass('mdui-appbar-with-tab'))
        body.addClass('mdui-appbar-with-tab');
}

function NoticeOnload() {
    document.title = '公告板';
    $('#drawer_notice').addClass('mdui-list-item-active');
    if (!body.hasClass('mdui-appbar-with-tab'))
        body.addClass('mdui-appbar-with-tab');
}

function DocsOnload() {
    document.title = '开发文档';
    $('#drawer_docs').addClass('mdui-list-item-active');
}

function InstallOnload() {
    document.title = '安装页面';
    $('#main_drawer_top').remove();
    $('#main_drawer').remove();
    $('body').removeClass('mdui-drawer-body-left');
}

//----------页面初始化 END----------


//----------登录、注册卡片切换----------
function ShowRegisterCard() {
    $('#login_card').hide();
    $('#register_card').show();
}

function ShowLoginCard() {
    $('#login_card').show();
    $('#register_card').hide();
}

//----------设置界面，修改用户信息对话框----------
function ChangeInfo(item) {
    mdui.prompt('请输入内容', '修改' + item,
        function (value) {
            mdui.dialog({
                title: '修改' + item,
                content: '请确认是否将' + item + '修改为：' + value,
                cssClass: 'mdui-color-blue-50',
                buttons: [
                    {
                        text: '取消'
                    },
                    {
                        text: '确认',
                        onClick: function () {
                            $.ajax({
                                method: 'POST',
                                url: './function/function.php',
                                data: {
                                    change_info: item,
                                    value: value,
                                },
                                success: function (data) {
                                    ShowDialog('修改' + item, data, '2000');
                                }
                            }).then(function () {
                                setTimeout(function () {
                                    //自动刷新页面，以显示修改后的内容
                                    location.reload();
                                }, 2100);
                            });
                        }
                    }
                ]
            });
        },
        function () {
        },
        {
            confirmOnEnter: true,
            defaultValue: '请输入' + item + '…',
            confirmText: '确认修改',
            cancelText: '取消'
        }
    );
}

//----------设置界面功能----------
$('#setting_id').on('click', function () {
    ShowDialog('禁止操作', '抱歉！用户Id由系统自动生成，不允许用户自行修改！', '2200');
});

$('#setting_name').on('click', function () {
    ChangeInfo('用户姓名');
});

$('#setting_email').on('click', function () {
    ChangeInfo('电子邮件');
});

$('#setting_date').on('click', function () {
    ShowDialog('禁止操作', '抱歉！用户注册时间由系统自动生成，不允许用户自行修改！', '2200');
});

$('#setting_sign').on('click', function () {
    ChangeInfo('个性签名');
});

$('#setting_age').on('click', function () {
    ChangeInfo('年龄');
});

$('#setting_sex').on('click', function () {
    ChangeInfo('性别');
});

$('#setting_tel').on('click', function () {
    ChangeInfo('电话');
});

$('#setting_pwd').on('click', function () {
    mdui.prompt('请验证原密码', '修改密码',
        function (value) {
            $.ajax({
                //使用ajax调用function.php，验证初始密码是否正确
                method: 'POST',
                url: './function/function.php',
                data: {
                    change_info: '密码验证',
                    value: value,
                },
                success: function (data) {
                    if (data === '验证通过') {
                        mdui.prompt('请输入新密码', '修改密码',
                            function (value) {
                                mdui.dialog({
                                    title: '修改密码',
                                    content: '请确认是否将密码修改为：' + value,
                                    cssClass: 'mdui-color-blue-50',
                                    buttons: [
                                        {
                                            text: '取消'
                                        },
                                        {
                                            text: '确认',
                                            onClick: function () {
                                                $.ajax({
                                                    //使用ajax调用function.php，修改密码
                                                    method: 'POST',
                                                    url: './function/function.php',
                                                    data: {
                                                        change_info: '密码',
                                                        value: value,
                                                    },
                                                    success: function (data) {
                                                        ShowDialog('修改密码', data, '2000');
                                                    }
                                                }).then(function () {
                                                });
                                            }
                                        }
                                    ]
                                });
                            },
                            function () {
                            },
                            {
                                confirmOnEnter: true,
                                defaultValue: '请输入新密码…',
                                confirmText: '确认修改',
                                cancelText: '取消'
                            }
                        );
                    } else {
                        ShowDialog('验证失败', '验证失败！错误原因为：' + data, '2000');
                    }
                }
            }).then(function () {
            });
        },
        function () {
        },
        {
            confirmOnEnter: true,
            defaultValue: '请验证原始密码…',
            confirmText: '确认修改',
            cancelText: '取消'
        }
    );
});

$('#setting_change_type').on('click', function () {
    //
});

$('#setting_delete_account').on('click', function () {
    //
});

//修改个性化配置函数
function ChangeColor(dia, item, setting) {
    var inst = new mdui.Dialog('#' + dialog);
    inst.open();
    var dialog = document.getElementById(dia);
    $.ajax({
        //使用ajax调用function.php，获取当前主题色
        method: 'POST',
        url: './function/function.php',
        data: {
            get_theme: item,
        },
        success: function (data) {
            //将当前主题色的单选框选中
            var obj = document.getElementsByName(setting);
            for (var i = 0; i < obj.length; i++) {
                if (obj[i].value === data) {
                    mdui.$(obj[i]).attr('checked', 'checked');
                }
            }
        }
    }).then(function () {
    });
    dialog.addEventListener('confirm.mdui.dialog', function () {
        var value;
        var obj = document.getElementsByName(setting);
        for (var i = 0; i < obj.length; i++) {
            if (obj[i].checked) {
                value = obj[i].value;
            }
        }
        $.ajax({
            //使用ajax调用function.php，修改主题色
            method: 'POST',
            url: './function/function.php',
            data: {
                change_info: item,
                value: value,
            },
            success: function (data) {
                ShowDialog('修改' + item, data, '1300');
            }
        }).then(function () {
            setTimeout(function () {
                //自动刷新页面，以显示修改后的内容
                location.reload();
            }, 1320);
        });
    });
}


//主题色
$('#setting_theme').on('click', function () {
    ChangeColor('dialog_theme_color', '主题色', 'setting_theme_color');
});

//主题强调色
$('#setting_theme_accent').on('click', function () {
    ChangeColor('dialog_theme_accent_color', '主题强调色', 'setting_theme_accent_color');
});

//表格配色
$('#setting_theme_table').on('click', function () {
    ChangeColor('dialog_theme_table', '表格配色', 'setting_theme_table');
});

$("input[name='setting_theme_color']").on('change', function () {
    //
});

//----------设置界面功能 END----------


//----------顶部菜单按钮功能----------
$('#head_menu_refresh').on('click', function () {
    location.reload();
});

$('#head_menu_settings').on('click', function () {
    location.href = './settings.php';
});

$('#head_menu_logout').on('click', function () {
    location.href = './function/function.php?action=logout';
});

$('#head_menu_login').on('click', function () {
    location.href = './login.php';
});

$('#head_menu_docs').on('click', function () {
    location.href = './docs.php';
});
//----------顶部菜单按钮功能 END----------


//----------抽屉导航栏功能----------
$('#drawer_index').on('click', function () {
    location.href = './index.php';
});

$('#drawer_center').on('click', function () {
    location.href = './center.php';
});

$('#drawer_logout').on('click', function () {
    location.href = './function/function.php?action=logout';
});

$('#drawer_settings').on('click', function () {
    location.href = './settings.php';
});

$('#drawer_management').on('click', function () {
    location.href = './management.php';
});

$('#drawer_course').on('click', function () {
    location.href = './course.php';
});

$('#drawer_score').on('click', function () {
    location.href = './score.php';
});

$('#drawer_notice').on('click', function () {
    location.href = './notice.php';
});

$('#drawer_docs').on('click', function () {
    location.href = './docs.php';
});

$('#drawer_drxs').on('click', function () {
    window.open('https://www.wangyusong.cn');
});

$('#drawer_mdui').on('click', function () {
    window.open('https://www.mdui.org');
});

$('#drawer_w3school').on('click', function () {
    window.open('https://www.w3school.com.cn');
});
//----------抽屉导航栏功能 END ----------

//----------个人中心页面点击事件绑定----------
$('#center_more_course').on('click', function () {
    location.href = './course.php';
});

$('#center_more_score').on('click', function () {
    location.href = './score.php';
});

$('#center_more_teaching').on('click', function () {
    location.href = './course.php#teaching_course';
});

$('#center_more_notice').on('click', function () {
    location.href = './notice.php';
});
//----------个人中心页面点击事件 END----------

//添加课程界面学时数据自动生成
$("input[name='add_course_credit']").on('change', function () {
    let credit = document.getElementsByName('add_course_credit');
    let hour = document.getElementsByName('add_course_hour');
    if (credit[0].value <= 0) {
        hour[0].value = credit[0].value * 16;
        document.getElementById('credit_val').innerText = '学分（仅支持正整数！）';
        $("#add_course_btn").prop('disabled', true);
    } else {
        hour[0].value = credit[0].value * 16;
        document.getElementById('credit_val').innerText = '学分';
        $("#add_course_btn").prop('disabled', false);
    }
});

$('#add_course_btn').on('click', function () {
    //添加课程
    let teacher = $("select[name='add_course_teacher']")[0];
    let classroom = $("select[name='add_course_classroom']")[0];
    if (teacher.value === 'none')
        ShowDialog('请选择教师', '请选择当前课程的主讲教师！', '2500');
    else if (classroom.value === 'none')
        ShowDialog('请选择教室', '请选择当前课程所使用的教室！', '2500');
    else {
        let name = $("input[name='add_course_name']")[0];
        let credit = $("input[name='add_course_credit']")[0];
        let hour = $("input[name='add_course_hour']")[0];
        let time = $("input[name='add_course_time']")[0];
        $.ajax({
            //使用ajax调用function.php，添加课程
            method: 'POST',
            url: './function/function.php',
            data: {
                add_course_btn: '',
                name: name.value,
                teacher: teacher.value,
                classroom: classroom.value,
                credit: credit.value,
                hour: hour.value,
                time: time.value
            },
            success: function (data) {
                ShowDialog('添加课程', data, '1500');
            }
        }).then(function () {
            setTimeout(function () {
                //自动刷新页面
                location.reload();
            }, 1510);
        });
    }
});

$('#add_score_btn').on('click', function () {
    //添加成绩
    let course = $("select[name='add_score_course']")[0];
    let student = $("select[name='add_score_student']")[0];
    let score = $("input[name='add_score_score']")[0];
    if (course.value === 'none')
        ShowDialog('请选择课程', '请选择待添加的课程名称！', '2000');
    else if (student.value === 'none')
        ShowDialog('请选择学生', '请选择待添加的学生姓名！', '2000');
    else if (score.value <= 0)
        //检查成绩信息是否为负值
        ShowDialog('成绩错误', '课程成绩填写有误，请重新填写！', '2000');
    else {
        $.ajax({
            //使用ajax调用function.php，添加成绩
            method: 'POST',
            url: './function/function.php',
            data: {
                add_score_btn: '',
                course: course.value,
                student: student.value,
                score: score.value,
            },
            success: function (data) {
                ShowDialog('添加成绩', data, '1500');
            }
        }).then(function () {
            setTimeout(function () {
                //自动刷新页面
                location.reload();
            }, 1510);
        });
    }
});

$('#release_notice_btn').on('click', function () {
    //发布公告
    let id = $("input[name='release_notice_id']")[0];
    let time = $("input[name='release_notice_time']")[0];
    let user = $("select[name='release_notice_user']")[0];
    let title = $("input[name='release_notice_title']")[0];
    let content = $("textarea[name='release_notice_content']")[0];
    $.ajax({
        //使用ajax调用function.php，发布公告
        method: 'POST',
        url: './function/function.php',
        data: {
            release_notice_btn: '',
            id: id.value,
            time: time.value,
            user: user.value,
            title: title.value,
            content: content.value
        },
        success: function (data) {
            ShowDialog('发布公告', data, '1500');
        }
    }).then(function () {
        setTimeout(function () {
            //自动刷新页面
            location.reload();
        }, 1510);
    });
});

//----------开发文档页面点击事件绑定----------
$('#docs_intro_card').on('click', function () {
    $('#docs_cards').hide();
    $('#docs_1').show();
});

$('#docs_cookie_card').on('click', function () {
    $('#docs_cards').hide();
    $('#docs_2').show();
});

$('#docs_db_card').on('click', function () {
    $('#docs_cards').hide();
    $('#docs_3').show();
});

$('#docs_code_card').on('click', function () {
    $('#docs_cards').hide();
    $('#docs_4').show();
});

$('#docs_update_card').on('click', function () {
    $('#docs_cards').hide();
    $('#docs_5').show();
});

$('#docs_feedback_card').on('click', function () {
    $('#docs_cards').hide();
    $('#docs_6').show();
});

$('#docs_back1').on('click', function () {
    $('#docs_1').hide();
    $('#docs_cards').show();
    scrollTo(0, 0);
});

$('#docs_next1').on('click', function () {
    $('#docs_1').hide();
    $('#docs_2').show();
    scrollTo(0, 0);
});

$('#docs_back2').on('click', function () {
    $('#docs_2').hide();
    $('#docs_1').show();
    scrollTo(0, 0);
});

$('#docs_next2').on('click', function () {
    $('#docs_2').hide();
    $('#docs_3').show();
    scrollTo(0, 0);
});

$('#docs_back3').on('click', function () {
    $('#docs_3').hide();
    $('#docs_2').show();
    scrollTo(0, 0);
});

$('#docs_next3').on('click', function () {
    $('#docs_3').hide();
    $('#docs_4').show();
    scrollTo(0, 0);
});

$('#docs_back4').on('click', function () {
    $('#docs_4').hide();
    $('#docs_3').show();
    scrollTo(0, 0);
});

$('#docs_next4').on('click', function () {
    $('#docs_4').hide();
    $('#docs_5').show();
    scrollTo(0, 0);
});

//----------开发文档页面点击事件 END----------

//----------添加新课程按钮----------
$('#btn_add_course_btn').on('click', function () {
    location.href = './course.php#add_course';
    location.reload();
});

//----------初始化安装页面功能----------
//测试数据库连接
$('#install_db_conn').on('click', function () {
    let host = document.getElementById('install_db_host');
    let name = document.getElementById('install_db_name');
    let user = document.getElementById('install_db_user');
    let pwd = document.getElementById('install_db_pwd');
    $.ajax({
        method: 'POST',
        url: './function/install_db.php',
        data: {
            install_db_conn: '',
            db_host: host.value,
            db_user: user.value,
            db_pwd: pwd.value,
            db_select: name.value
        },
        success: function (data) {
            if (data === '1') {
                $('#install_db_info')[0].innerText = '数据库连接成功！';
                $('#install_db_info').addClass('mdui-text-color-blue');
                $("#install_db_data").prop('disabled', false);
                $("#install_next_1").prop('disabled', false);
            } else {
                $('#install_db_info')[0].innerText = '数据库连接失败！';
                $('#install_db_info').addClass('mdui-text-color-red');
                $("#install_db_data").prop('disabled', true);
                $("#install_next_1").prop('disabled', true);
            }
        }
    }).then(function () {
    });
});

//导入示例数据
$('#install_db_data').on('click', function () {
    $.ajax({
        //使用ajax调用config.php，测试连接数据库
        method: 'POST',
        url: './function/function.php',
        data: {
            install_db_data: ''
        },
        success: function (data) {
            if (data === '1') {
                $('#install_db_data_info')[0].innerText = '示例数据导入成功！';
                $('#install_db_data_info').addClass('mdui-text-color-blue');
            } else {
                $('#install_db_data_info')[0].innerText = '示例数据导入失败！';
                $('#install_db_data_info').addClass('mdui-text-color-red');
            }
        }
    }).then(function () {
    });
});

$('#install_next_1').on('click', function () {
    let host = document.getElementById('install_db_host');
    let name = document.getElementById('install_db_name');
    let user = document.getElementById('install_db_user');
    let pwd = document.getElementById('install_db_pwd');
    //更新配置
    $.ajax({
        method: 'POST',
        url: './function/install_db.php',
        data: {
            update_conn: '',
            db_host: host.value,
            db_user: user.value,
            db_pwd: pwd.value,
            db_select: name.value
        },
        success: function (data) {
            //创建数据表
            $.ajax({
                method: 'POST',
                url: './function/function.php',
                data: {
                    init_db_table: '',
                    db_host: host.value,
                    db_user: user.value,
                    db_pwd: pwd.value,
                    db_select: name.value
                },
                success: function (data) {
                    if (data === '1') {
                        history.pushState(null, null, "install.php?step=2");
                        location.reload();
                    } else {
                        ShowDialog('创建失败', '抱歉，数据表创建失败，请稍后重试！', '2500');
                    }
                }
            }).then(function () {
            });
        }
    }).then(function () {
    });
});

$('#install_next_2').on('click', function () {
    history.pushState(null, null, "install.php?complete");
    location.reload();
});

$('#install_pre_2').on('click', function () {
    history.pushState(null, null, "install.php?step=1");
    location.reload();
});


$('#install_pre_3').on('click', function () {
    history.pushState(null, null, "install.php?step=2");
    location.reload();
});


//----------初始化安装页面功能 END----------

//----------删除安装文件----------
$('#delete_install_files').on('click', function () {
    mdui.dialog({
        title: '删除安装文件',
        content: '请确认是否删除相关安装文件，删除后若需重新安装，需要重新下载完整安装包！',
        cssClass: 'mdui-color-blue-50',
        buttons: [
            {
                text: '取消'
            },
            {
                text: '确认',
                onClick: function () {
                    $.ajax({

                        method: 'POST',
                        url: './function/function.php',
                        data: {
                            delete_install_files: '',
                        },
                        success: function (data) {
                            ShowDialog('删除安装文件', data, '2500');
                        }
                    }).then(function () {
                        setTimeout(function () {
                            $.ajax({
                                method: 'POST',
                                url: './function/function.php',
                                data: {
                                    delete_install_php: '',
                                },
                                success: function () {
                                    location.href = './login.php';
                                }
                            }).then(function () {
                            });
                        }, 2500);
                    });
                }
            }
        ]
    });
});

//----------删除安装文件 END----------

//----------重置自动登录有效期为30天----------
$('#reset_auto_login_time').on('click', function () {
    if (GetCookie('Token') === '') {
        ShowDialog('功能未开启', '抱歉，当前未开启自动登录功能，请开启后再使用更新时间功能！', '2500');
    } else {
        $.ajax({
            method: 'POST',
            url: './function/function.php',
            data: {
                reset_token_time: '',
            },
            success: function () {
                ShowDialog('更新成功', '恭喜，自动登录有效时间已更新为30天！', '2500');
            }
        }).then(function () {
            setTimeout(function () {
                //自动刷新页面
                location.reload();
            }, 2600);
        });
    }
});

//----------开启、关闭自动登录功能----------
$('#auto_login_switch').on('change', function () {
    let state = $('#auto_login_switch')[0].checked;
    if (state === true) {
        $.ajax({
            method: 'POST',
            url: './function/function.php',
            data: {
                auto_login_true: '',
            },
            success: function () {
            }
        }).then(function () {
            setTimeout(function () {
                //自动刷新页面
                location.reload();
            }, 100);
        });
    }
    if (state === false) {
        $.ajax({
            method: 'POST',
            url: './function/function.php',
            data: {
                auto_login_false: '',
            },
            success: function () {
            }
        }).then(function () {
            setTimeout(function () {
                //自动刷新页面
                location.reload();
            }, 100);
        });
    }
});